<template>
  <basePages>
    <view class="container">
      <!-- 顶部状态栏 -->
      <view class="status-bar">
        <view class="greeting-section">
          <text class="greeting">您好，{{ userStore.userData?.name || '家属' }}</text>
          <text class="date">{{ currentDate }}</text>
        </view>
        <view class="notification" @click="navigateTo('/pages/common/alert')">
          <image class="icon" src="/static/icons/notification.png"></image>
          <view class="badge" v-if="unreadCount > 0">{{ unreadCount }}</view>
        </view>
      </view>

      <!-- 老人卡片轮盘 -->
      <view class="elderly-section">
        <swiper class="elderly-swiper" :current="currentIndex" @change="handleSwiperChange" :circular="true"
          :previous-margin="'120rpx'" :next-margin="'120rpx'" :duration="300">
          <swiper-item v-for="(elderly, index) in bindingList" :key="elderly.id">
            <view class="elderly-card" :class="{ 'active': currentIndex === index }">
              <view class="card-header">
                <view class="avatar-wrapper" @click.stop="navigateToDetail(elderly.id)">
                  <image class="avatar" :src="elderly.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
                  <view class="alert-dot" v-if="hasHealthAlert(elderly)"></view>
                </view>
              </view>
              <view class="card-body">
                <view class="info-section">
                  <text class="name clickable" @click.stop="navigateToDetail(elderly.id)">{{ elderly.name }}</text>
                  <text class="age">{{ elderly.age }}岁</text>
                  <view class="health-tag" :class="getHealthStatusClass(elderly)">
                    {{ getHealthStatusText(elderly) }}
                  </view>
                </view>
              </view>
            </view>
          </swiper-item>
          <swiper-item>
            <view class="add-card" @click="showBindModal">
              <text class="add-icon">+</text>
              <text class="add-text">添加老人</text>
            </view>
          </swiper-item>
        </swiper>
        <!-- 轮盘指示器 -->
        <view class="swiper-dots">
          <view v-for="(elderly, index) in bindingList" :key="elderly.id" class="dot"
            :class="{ 'active': currentIndex === index }"></view>
        </view>
      </view>

      <!-- 健康数据展示 -->
      <view class="health-data-section" v-if="currentElderly">
        <view class="health-data-card">
          <view class="health-item">
            <text class="label">血压</text>
            <text class="value"
              :class="getBloodPressureClass(healthData.getRealtimeHealthData.bloodPressureHigh, healthData.getRealtimeHealthData.bloodPressureLow)">
              {{ ((healthData.getRealtimeHealthData.bloodPressureHigh||'--') + '/' +
                (healthData.getRealtimeHealthData.bloodPressureLow||'--')) || '--' }}
            </text>
            <text class="unit">mmHg</text>
            <text class="status-text"
              :class="getBloodPressureClass(healthData.getRealtimeHealthData.bloodPressureHigh, healthData.getRealtimeHealthData.bloodPressureLow)">
              {{
                getBloodPressureStatus(healthData.getRealtimeHealthData.bloodPressureHigh, healthData.getRealtimeHealthData.bloodPressureLow)
              }}
            </text>
          </view>
          <view class="health-item">
            <text class="label">心率</text>
            <text class="value" :class="getHeartRateClass(healthData.getRealtimeHealthData.heartRate)">
              {{ healthData.getRealtimeHealthData.heartRate || '--' }}
            </text>
            <text class="unit">次/分</text>
            <text class="status-text" :class="getHeartRateClass(healthData.getRealtimeHealthData.heartRate)">
              {{ getHeartRateStatus(healthData.getRealtimeHealthData.heartRate) }}
            </text>
          </view>
          <view class="health-item">
            <text class="label">血氧</text>
            <text class="value" :class="getBloodOxygenClass(healthData.getRealtimeHealthData.bloodOxygen)">
              {{ healthData.getRealtimeHealthData.bloodOxygen || '--' }}
            </text>
            <text class="unit">%</text>
            <text class="status-text" :class="getBloodOxygenClass(healthData.getRealtimeHealthData.bloodOxygen)">
              {{ getBloodOxygenStatus(healthData.getRealtimeHealthData.bloodOxygen) }}
            </text>
          </view>
        </view>
      </view>

      <!-- 快捷功能入口 -->
      <view class="quick-actions">
        <view class="action-item" :class="{ 'disabled': currentIndex === bindingList.length }"
          @click="currentIndex < bindingList.length && navigateTo('/pages/common/healthCondition')">
          <image class="action-icon" src="/static/icons/ecg.png"></image>
          <text class="action-text">健康档案</text>
        </view>
        <!-- <view class="action-item" :class="{ 'disabled': currentIndex === bindingList.length }"
          @click="currentIndex < bindingList.length && navigateTo('/pages/role/older/medicineRemind')">
          <image class="action-icon" src="/static/icons/medicine.png"></image>
          <text class="action-text">用药提醒</text>
        </view> -->
        <view class="action-item" :class="{ 'disabled': currentIndex === bindingList.length }"
          @click="currentIndex < bindingList.length && navigateTo('/pages/common/record')">
          <image class="action-icon" src="/static/icons/medical.png"></image>
          <text class="action-text">医疗记录</text>
        </view>
        <view class="action-item" :class="{ 'disabled': currentIndex === bindingList.length }"
          @click="currentIndex < bindingList.length && navigateTo('/pages/shared/devices/deviceList')">
          <image class="action-icon" src="/static/icons/settings.png"></image>
          <text class="action-text">设备管理</text>
        </view>
        <view class="action-item" :class="{ 'disabled': currentIndex === bindingList.length }"
          @click="currentIndex < bindingList.length && navigateTo('/pages/common/AI')">
          <image class="action-icon" src="/static/icons/ai.png"></image>
          <text class="action-text">AI助手</text>
        </view>
      </view>

      <!-- 绑定老人模态框 -->
      <view class="modal-mask" v-if="showModal" @click="closeModal"></view>
      <view class="bind-modal" v-if="showModal" :class="{ 'show': showModal }">
        <view class="modal-content">
          <view class="modal-header">
            <text class="modal-title">绑定老人</text>
            <text class="modal-close" @click="closeModal">×</text>
          </view>
          <view class="modal-body">
            <view class="form-item">
              <text class="form-label">手机号码</text>
              <view class="input-wrapper">
                <input v-model="bindForm.phone" placeholder="请输入老人手机号" class="modal-input" type="number"
                  maxlength="11" />
              </view>
            </view>
            <view class="form-item">
              <text class="form-label">密码</text>
              <view class="input-wrapper">
                <input v-model="bindForm.password" placeholder="请输入老人密码" class="modal-input" type="password" password />
              </view>
            </view>
            <view class="form-tips">
              <text class="tips-text">提示：请确保老人已注册账号</text>
            </view>
          </view>
          <view class="modal-footer">
            <button class="modal-btn cancel" @click="closeModal">取消</button>
            <button class="modal-btn confirm" @click="bindElderly" :disabled="isBinding">
              <text v-if="!isBinding">确定</text>
              <view v-else class="loading-icon"></view>
            </button>
          </view>
        </view>
      </view>
    </view>
  </basePages>
</template>

<script setup>
import { ref, onMounted, computed, capitalize } from 'vue';
import { useBindingStore } from '../../../store/modules/useBindingStore';
import { useUserStore } from '../../../store/modules/useUserStore';
import { useHealthData } from '../../../store/modules/useHealthData';
import { loginAPI } from '../../../API/auth/login';

const bindingStore = useBindingStore();
const userStore = useUserStore();
const healthData = useHealthData();




// 模拟数据
const bindingList = ref([
  {
    id: 1,
    name: '张爷爷',
    age: 75,
    avatar: '/static/avatar1.png',
    bloodPressure: '120/80',
    heartRate: '75',
    bloodOxygen: '98%',
    healthStatus: 'normal'
  },
  {
    id: 2,
    name: '李奶奶',
    age: 68,
    avatar: '/static/avatar2.png',
    bloodPressure: '135/85',
    heartRate: '82',
    bloodOxygen: '96%',
    healthStatus: 'warning'
  },
  {
    id: 3,
    name: '王爷爷',
    age: 82,
    avatar: '/static/avatar3.png',
    bloodPressure: '118/78',
    heartRate: '72',
    bloodOxygen: '97%',
    healthStatus: 'normal'
  }
]);

const currentIndex = ref(0);
const unreadCount = ref(2);
const showModal = ref(false);
const isBinding = ref(false);

const bindForm = ref({
  phone: '',
  password: ''
});

onMounted(async () => {
  // 实际项目中应该从API获取数据
  try {

    await bindingStore.fetchBindingList();

    bindingList.value = bindingStore.getBindingList;
    if (bindingList.value.length > 0 && bindingStore.getCurBindingId) {
      await healthData.fetchRealtimeData();
    }

  } catch (error) {
    console.log(error)
  }

});

const handleSwiperChange = (e) => {
  try {

    currentIndex.value = e.detail.current;
    if (currentIndex.value < bindingList.value.length) {
      bindingStore.setCurBindingId(bindingList.value[currentIndex.value].id);
      healthData.setCurUserId(bindingList.value[currentIndex.value].id)
    }

    if (bindingList.value.length > 0 && bindingStore.getCurBindingId) {
      healthData.fetchRealtimeData();
    }
  } catch (error) {
    console.log('swiperChange:',error)
    healthData.setRealtimeHealthData({})
  }

};

const navigateTo = (url) => {
  uni.navigateTo({ url });
};

const showBindModal = () => {
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
  bindForm.value = {
    phone: '',
    password: ''
  };
};

const bindElderly = async () => {
  if (isBinding.value) return;

  if (!bindForm.value.phone || !bindForm.value.password) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }

  isBinding.value = true;
  try {
    // 模拟绑定成功
    // await new Promise(resolve => setTimeout(resolve, 1000));
    const auth = { phone: bindForm.value.phone, password: bindForm.value.password };
    const user = await loginAPI(auth)
    if (user && user.code == 200) {
      const userId = user?.data.userData.id
      bindingStore.addBinding({ userId: userStore.curUserId, bindedUserId: userId, relation: 'realtion' })
    }


    uni.showToast({
      title: '绑定成功',
      icon: 'success'
    });

    closeModal();
    // 刷新列表
    // await bindingStore.fetchBindingList();
    // bindingList.value = bindingStore.getBindingList;
  } catch (error) {
    uni.showToast({
      title: '绑定失败',
      icon: 'none'
    });
  } finally {
    isBinding.value = false;
  }
};

const getHealthStatusClass = (elderly) => {
  return elderly.healthStatus === 'normal' ? 'normal' : 'warning';
};

const getHealthStatusText = (elderly) => {
  return elderly.healthStatus === 'normal' ? '状态良好' : '需要关注';
};

const hasHealthAlert = (elderly) => {
  return elderly.healthStatus !== 'normal';
};

const getBloodPressureClass = (systolic, diastolic) => {
  if(!systolic || !diastolic){
    return '';
  }
  // if (!value) return '';
  // const [systolic, diastolic] = value.split('/').map(Number);
  if (systolic > 140 || diastolic > 90) return 'warning';
  if (systolic < 90 || diastolic < 60) return 'warning';
  return 'normal';
};

const getHeartRateClass = (value) => {
  if (!value) return '';
  const rate = Number(value);
  if (rate > 100 || rate < 60) return 'warning';
  return 'normal';
};

const getBloodOxygenClass = (value) => {
  if (!value) return '';
  const oxygen = Number(value);
  if (oxygen < 95) return 'warning';
  return 'normal';
};

const currentElderly = computed(() => {
  if (currentIndex.value < bindingList.value.length) {
    return bindingList.value[currentIndex.value];
  }
  return null;
});

const currentDate = computed(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const weekday = weekdays[now.getDay()];
  return `${year}年${month}月${day}日 ${weekday}`;
});

const getBloodPressureStatus = (systolic, diastolic) => {
  // if (!value) return '--';
  // const [systolic, diastolic] = value.split('/').map(Number);
  if (systolic > 140 || diastolic > 90) return '偏高';
  if (systolic < 90 || diastolic < 60) return '偏低';
  return '正常';
};

const getHeartRateStatus = (value) => {
  if (!value) return '--';
  const rate = Number(value);
  if (rate > 100) return '偏快';
  if (rate < 60) return '偏慢';
  return '正常';
};

const getBloodOxygenStatus = (value) => {
  if (!value) return '--';
  const oxygen = Number(value);
  if (oxygen < 95) return '偏低';
  return '正常';
};

const navigateToDetail = (elderlyId) => {
  console.log('Navigating to detail page for elderly:', elderlyId);
  if (elderlyId) {
    uni.navigateTo({
      url: `/pages/role/family/elderlyDetail?id=${elderlyId}`,
      success: () => {
        console.log('Navigation successful');
      },
      fail: (err) => {
        console.error('Navigation failed:', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding: 20rpx;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  background: linear-gradient(135deg, #fff 0%, #f0f7ff 100%);
  padding: 20rpx 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.08);

  .greeting-section {
    .greeting {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
      display: block;
    }

    .date {
      font-size: 24rpx;
      color: #999;
    }
  }

  .notification {
    position: relative;
    padding: 20rpx;

    .icon {
      width: 48rpx;
      height: 48rpx;
    }

    .badge {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      background-color: #FF6B6B;
      color: #fff;
      font-size: 20rpx;
      padding: 4rpx 10rpx;
      border-radius: 20rpx;
      min-width: 32rpx;
      text-align: center;
      box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
    }
  }
}

.elderly-section {
  margin-bottom: 30rpx;

  .elderly-swiper {
    height: 360rpx;
  }

  .elderly-card {
    height: 100%;
    background: linear-gradient(135deg, #fff 0%, #f0f7ff 100%);
    border-radius: 30rpx;
    padding: 30rpx;
    box-shadow: 0 8rpx 24rpx rgba(33, 150, 243, 0.15);
    display: flex;
    flex-direction: column;
    transition: all 0.3s ease;
    transform: scale(0.9);
    opacity: 0.8;

    &.active {
      transform: scale(1);
      opacity: 1;
      box-shadow: 0 12rpx 36rpx rgba(33, 150, 243, 0.2);
    }

    .card-header {
      position: relative;
      text-align: center;
      margin-bottom: 20rpx;

      .avatar-wrapper {
        position: relative;
        display: inline-block;
        cursor: pointer;
        
        &:active {
          opacity: 0.8;
        }
      }

      .avatar {
        width: 140rpx;
        height: 140rpx;
        border-radius: 70rpx;
        border: 4rpx solid #fff;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
      }

      .alert-dot {
        position: absolute;
        top: 20rpx;
        right: 50%;
        margin-right: -70rpx;
        width: 20rpx;
        height: 20rpx;
        background-color: #f44336;
        border-radius: 50%;
        border: 4rpx solid #fff;
        animation: pulse 2s infinite;
      }
    }

    .card-body {
      text-align: center;

      .info-section {
        .name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
          display: block;
        }

        .age {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 12rpx;
          display: block;
        }

        .health-tag {
          display: inline-block;
          font-size: 22rpx;
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
          transition: all 0.3s ease;

          &.normal {
            background-color: #e8f5e9;
            color: #4caf50;
          }

          &.warning {
            background-color: #ffebee;
            color: #f44336;
          }
        }
      }
    }
  }

  .add-card {
    height: 100%;
    background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
    border-radius: 30rpx;
    border: 2rpx dashed #ddd;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transform: scale(0.9);
    opacity: 0.8;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
      opacity: 1;
    }

    .add-icon {
      font-size: 60rpx;
      color: #FF6B6B;
      margin-bottom: 16rpx;
    }

    .add-text {
      font-size: 28rpx;
      color: #666;
    }
  }

  .swiper-dots {
    display: flex;
    justify-content: center;
    margin-top: 20rpx;

    .dot {
      width: 12rpx;
      height: 12rpx;
      border-radius: 6rpx;
      background-color: #ddd;
      margin: 0 8rpx;
      transition: all 0.3s ease;

      &.active {
        width: 24rpx;
        background-color: #FF6B6B;
      }
    }
  }
}

.health-data-section {
  margin-bottom: 40rpx;
  padding: 0 20rpx;

  .health-data-card {
    background: linear-gradient(135deg, #fff 0%, #f0f7ff 100%);
    border-radius: 20rpx;
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.08);
    position: relative;

    .health-item {
      text-align: center;
      flex: 1;
      position: relative;

      &:not(:last-child)::after {
        content: '';
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1rpx;
        height: 60%;
        background-color: #eee;
      }

      .label {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 12rpx;
        display: block;
      }

      .value {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
        display: block;
        transition: all 0.3s ease;

        &.normal {
          color: #4caf50;
        }

        &.warning {
          color: #f44336;
        }
      }

      .unit {
        font-size: 22rpx;
        color: #999;
        margin-bottom: 8rpx;
        display: block;
      }

      .status-text {
        font-size: 22rpx;
        display: block;

        &.normal {
          color: #4caf50;
        }

        &.warning {
          color: #f44336;
        }
      }
    }
  }
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
  margin: 0 20rpx 40rpx;
  padding: 0;

  .action-item {
    background: linear-gradient(135deg, #fff 0%, #f0f7ff 100%);
    border-radius: 20rpx;
    padding: 36rpx 24rpx;
    text-align: center;
    box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.08);
    transition: all 0.3s ease;

    &:nth-child(1) {
      background: linear-gradient(135deg, #fff 0%, #e8f5e9 100%);
    }

    &:nth-child(2) {
      background: linear-gradient(135deg, #fff 0%, #fff3e0 100%);
    }

    &:nth-child(3) {
      background: linear-gradient(135deg, #fff 0%, #e3f2fd 100%);
    }

    &:nth-child(4) {
      background: linear-gradient(135deg, #fff 0%, #f3e5f5 100%);
    }

    &:nth-child(5) {
      background: linear-gradient(135deg, #fff 0%, #e8eaf6 100%);
    }

    &:active {
      transform: scale(0.98);
      box-shadow: 0 2rpx 8rpx rgba(33, 150, 243, 0.1);
    }

    &.disabled {
      opacity: 0.5;
      pointer-events: none;
      background: linear-gradient(135deg, #f5f5f5 0%, #f0f0f0 100%);
      box-shadow: none;

      .action-icon {
        filter: grayscale(100%);
      }

      .action-text {
        color: #999;
      }
    }

    .action-icon {
      width: 64rpx;
      height: 64rpx;
      margin-bottom: 16rpx;
      transition: all 0.3s ease;
    }

    .action-text {
      font-size: 26rpx;
      color: #333;
      transition: all 0.3s ease;
    }
  }
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
  
  &:active {
    opacity: 0.8;
  }
}

.clickable {
  cursor: pointer;
  
  &:active {
    opacity: 0.8;
  }
}

.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 999;
  backdrop-filter: blur(4px);
}

.bind-modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0.8);
  width: 85%;
  background-color: #fff;
  border-radius: 30rpx;
  z-index: 1000;
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.show {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }

  .modal-content {
    padding: 40rpx;

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 40rpx;
      padding-bottom: 20rpx;
      border-bottom: 1rpx solid #f5f5f5;

      .modal-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }

      .modal-close {
        font-size: 48rpx;
        color: #999;
        padding: 10rpx;
        line-height: 1;
      }
    }

    .modal-body {
      .form-item {
        margin-bottom: 30rpx;

        .form-label {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 16rpx;
          display: block;
        }

        .input-wrapper {
          position: relative;
          background-color: #f8f9fa;
          border-radius: 16rpx;
          padding: 4rpx;
          transition: all 0.3s ease;

          &:focus-within {
            background-color: #fff;
            box-shadow: 0 0 0 2rpx rgba(255, 107, 107, 0.2);
          }

          .modal-input {
            width: 100%;
            height: 88rpx;
            border: none;
            border-radius: 12rpx;
            padding: 0 24rpx;
            font-size: 28rpx;
            background-color: transparent;
            color: #333;

            &::placeholder {
              color: #999;
            }
          }
        }
      }

      .form-tips {
        margin-top: 20rpx;
        padding: 16rpx 24rpx;
        background-color: #f8f9fa;
        border-radius: 12rpx;

        .tips-text {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .modal-footer {
      display: flex;
      justify-content: space-between;
      margin-top: 40rpx;
      gap: 20rpx;

      .modal-btn {
        flex: 1;
        height: 88rpx;
        border-radius: 16rpx;
        font-size: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;

        &.cancel {
          background-color: #f5f5f5;
          color: #666;

          &:active {
            background-color: #eee;
          }
        }

        &.confirm {
          background-color: #FF6B6B;
          color: #fff;

          &:active {
            background-color: darken(#FF6B6B, 5%);
          }

          &:disabled {
            opacity: 0.6;
          }

          .loading-icon {
            width: 40rpx;
            height: 40rpx;
            border: 4rpx solid #fff;
            border-top-color: transparent;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
          }
        }
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }

  50% {
    transform: scale(1.2);
    opacity: 0.8;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
